<template>
	<view>
		<view style="width:92%;margin:10px auto;">
			<image :src="codepic" mode="widthFix"></image>
		</view>
		<view class="erweima" @tap="toShare">保存二维码</view>
	</view>
</template>

<script setup lang="ts">
	import { onShow, onLoad, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app'
	import { ref, watch } from 'vue'
	import { fullUrl } from '@/utils/common'
	import { fenxiangApi } from '@/api/peiwan'

	const codepic = ref('');
	const codePic = () => {
		fenxiangApi().then((res) => {
			codepic.value = res.result.qrCodeUR
		})
	}
	const tempFilePath = ref('');
	const toShare = () => {
		uni.showLoading({ title: '正在保存图片...' });
		// 下载图片
		uni.downloadFile({
			url: codepic.value,
			success: (res) => {
				if (res.statusCode === 200) {
					console.log('666666',res);
					tempFilePath.value = res.tempFilePath; // 获取下载后的图片临时路径

					// 检查并请求写入相册权限
					uni.getSetting({
						success: (settingRes) => {
							if (!settingRes.authSetting['scope.writePhotosAlbum']) {
								// 用户未授权，发起授权请求
								uni.authorize({
									scope: 'scope.writePhotosAlbum',
									success: () => {
										// 用户同意授权，保存图片到相册
										saveImageToPhotosAlbum();
									},
									fail: () => {
										// 用户拒绝授权，提示用户去设置页面授权
										uni.showModal({
											title: '提示',
											content: '您拒绝了写入相册的权限，请去设置页面开启权限后重试。',
											success: (modalRes) => {
												if (modalRes.confirm) {
													uni.openSetting(); // 调起客户端小程序设置界面
												}
											}
										});
										uni.hideLoading()
									}
								});
							} else {
								// 用户已授权，直接保存图片到相册
								saveImageToPhotosAlbum();
							}
						}
					});
				} else {
					uni.showToast({ title: '图片下载失败', icon: 'none' });
				}
			}
		})
	}

	// 保存图片到相册的实际操作
	const saveImageToPhotosAlbum = () => {
		uni.saveImageToPhotosAlbum({
			filePath: tempFilePath.value,
			success: () => {
				uni.showToast({ title: '图片已保存到相册', icon: 'success' });
			},
			fail: (err) => {
				if (err.errMsg === 'saveImageToPhotosAlbum:fail auth deny') {
					uni.showToast({ title: '您未授权写入相册，请去设置页面开启权限。', icon: 'none' });
				} else {
					uni.showToast({ title: '图片保存失败', icon: 'none' });
				}
			}
		});
	}
	onLoad(() => {
		codePic()
	})
</script>

<style>
	page {
		background-color: #f6f6f6;
	}

	.erweima {
		width: 92%;
		height: 200px;
		line-height: 200px;
		margin: 0 auto;
		font-size: 23px;
		font-weight: bolder;
		text-align: center;
	}
</style>